<template>
  <view class="content">
    <!-- 页面头部区域，包含搜索框和店铺信息展示 -->
    <view class="header">
      <!-- 搜索框，用户可在此输入商品名称进行搜索 -->
      <view class="search">
        <input
          type="text"
          placeholder="请输入商品名称"
          style="padding-left: 40px"
        />
      </view>
      <!-- 循环展示店铺信息，每个店铺信息包含图片、名称、月售、起送条件、基础运费和标语 -->
      <view class="listcontent" v-for="shop in shops" :key="shop.id">
        <view class="listitem">
          <img class="shop-image" :src="shop.imgUrl" />
        </view>
        <view class="listitem listcon">
          {{ shop.name }}
          <view class="listrow">
            <view>月售：{{ shop.sales }}</view>
            <view>起送：{{ shop.expressLimit }}</view>
            <view>基础运费：{{ shop.expressPrice }}</view>
          </view>
          <view class="slogan">{{ shop.slogan }}</view>
        </view>
      </view>
    </view>
    <!-- 中间商品分类和商品列表区域 -->
    <view class="middleshops">
      <!-- 商品分类切换按钮区域 -->
      <view class="click">
        <!-- 全部商品按钮，点击可切换到全部商品列表，通过动态类名控制按钮样式 -->
        <view
          class="item"
          :class="{ active: index === 1 }"
          @click="switchView(1)"
          >全部商品</view
        >
        <!-- 秒杀按钮，点击可切换到秒杀商品列表，通过动态类名控制按钮样式 -->
        <view
          class="item"
          :class="{ active: index === 2 }"
          @click="switchView(2)"
          >秒杀</view
        >
        <!-- 新鲜水果按钮，点击可切换到新鲜水果商品列表，通过动态类名控制按钮样式 -->
        <view
          class="item"
          :class="{ active: index === 3 }"
          @click="switchView(3)"
          >新鲜水果</view
        >
      </view>
      <!-- 商品列表展示区域，根据不同的分类标志（flag）展示对应的商品列表 -->
      <view class="message">
        <!-- 当flag为1时，展示全部商品列表 -->
        <view v-if="flag === 1" class="i">
          <view class="shop">
            <!-- 循环展示每个商品信息，包括图片、名称、月售、价格、原价和加入购物车按钮 -->
            <view class="itemlist" v-for="p in products" :key="p.id">
              <view class="con"
                ><img class="product-image" :src="p.imgUrl"
              /></view>
              <view class="con">
                <view class="title">{{ p.name }}</view>
                <view>月售 {{ p.sales }}</view>
                <view class="row">
                  <view class="price">￥{{ p.price }}</view>
                  <view class="oldPrice">￥{{ p.oldPrice }}</view>
                </view>
              </view>
              <view class="con button">
                <!-- 加入购物车按钮，点击调用buttonhaddcart方法将商品加入购物车 -->
                <view @click="buttonhaddcart(p)"
                  ><button>加入购物车</button></view
                >
              </view>
            </view>
          </view>
        </view>
        <!-- 当flag为2时，展示秒杀商品列表 -->
        <view v-if="flag === 2" class="i">
          <view class="shop">
            <view class="itemlist" v-for="p in products" :key="p.id">
              <view class="con"
                ><img class="product-image" :src="p.imgUrl"
              /></view>
              <view class="con">
                <view class="title">{{ p.name }}</view>
                <view>月售 {{ p.sales }}</view>
                <view class="row">
                  <view class="price">￥{{ p.price }}</view>
                  <view class="oldPrice">￥{{ p.oldPrice }}</view>
                </view>
              </view>
              <view class="con button">
                <view @click="buttonhaddcart(p)"
                  ><button>加入购物车</button></view
                >
              </view>
            </view>
          </view>
        </view>
        <!-- 当flag为3时，展示新鲜水果商品列表 -->
        <view v-if="flag === 3" class="i">
          <view class="shop">
            <view class="itemlist" v-for="p in products" :key="p.id">
              <view class="con"
                ><img class="product-image" :src="p.imgUrl"
              /></view>
              <view class="con">
                <view class="title">{{ p.name }}</view>
                <view>月售 {{ p.sales }}</view>
                <view class="row">
                  <view class="price">￥{{ p.price }}</view>
                  <view class="oldPrice">￥{{ p.oldPrice }}</view>
                </view>
              </view>
              <view class="con button">
                <view @click="buttonhaddcart(p)"
                  ><button>加入购物车</button></view
                >
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="cart-icon" @click="toggleCart">
      <img class="cart-icon-image" src="/static/icon/菜篮子.png">
      <view class="cart-badge" v-if="totalQuantity > 0">{{ totalQuantity }}</view>
    </view>

    <!-- 购物车面板 -->
    <view class="cart-panel" :class="{ show: showCart }">
      <view class="cart-header">
        <view class="cart-title">购物车</view>
        <view class="clear-cart" @click="clearCurrentSupermarketCart">清空购物车</view>
      </view>
      
      <view class="cart-items">
        <view class="cart-item" v-for="(item, index) in filteredCartList" :key="index">
          <view class="item-select" @click="toggleItemSelect(item)">
            <uni-icons :type="item.selected ? 'checkbox-filled' : 'circle'" color="#1aad19"></uni-icons>
          </view>
          <view class="item-image">
            <img class="cart-item-image" :src="item.imgUrl" />
          </view>
          <view class="item-info">
            <view class="item-name">{{ item.name }}</view>
            <view class="item-price">¥{{ item.price }}</view>
          </view>
          <view class="item-quantity">
            <view class="quantity-btn" @click="decreaseQuantity(item)">-</view>
            <view class="quantity-number">{{ item.quantity }}</view>
            <view class="quantity-btn" @click="increaseQuantity(item)">+</view>
          </view>
        </view>
      </view>
      
      <view class="cart-footer">
        <view class="select-all" @click="toggleSelectAll">
          <uni-icons :type="isAllSelected ? 'checkbox-filled' : 'circle'" color="#1aad19"></uni-icons>
          <text>全选</text>
        </view>
        <view class="total-price">
          合计: <text class="price">¥{{ totalPrice }}</text>
        </view>
        <view class="checkout-btn" @click="checkout">去结算({{ selectedCount }})</view>
      </view>
    </view>
    
    <!-- 遮罩层 -->
    <view class="overlay" v-if="showCart" @click="toggleCart"></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopid: "",
      shops: [],
      products: [],
      flag: 1,
      index: 1,
      cartlist: [], // 购物车数据
      showCart: false, // 控制购物车信息是否显示
    };
  },
   
  computed: {
    // 过滤出本超市的购物车商品
    filteredCartList() {
      return this.cartlist.filter(item => item.shopId === this.shopid);
    },
    // 选中的商品
    selectedItems() {
      return this.filteredCartList.filter(item => item.selected);
    },
    // 选中商品的总数量
    selectedCount() {
      return this.selectedItems.reduce((sum, item) => sum + item.quantity, 0);
    },
    // 购物车中所有商品的总数量
    totalQuantity() {
      return this.filteredCartList.reduce((sum, item) => sum + item.quantity, 0);
    },
    // 选中商品的总价格
    totalPrice() {
      return this.selectedItems.reduce((sum, item) => sum + (item.price * item.quantity), 0).toFixed(2);
    },
    // 是否全选
    isAllSelected() {
      return this.filteredCartList.length > 0 && 
             this.filteredCartList.every(item => item.selected);
    }
  },
  onLoad(options) {
    const id2 = options.id;
    this.shopid = options.id;
    this.shopsdata(id2);
    this.switchView(1);

    // 初始化时加载购物车数据
    this.loadCartData();
  },
  methods: {
    // 加载购物车数据
    loadCartData() {
      try {
        const cartData = uni.getStorageSync("cartlist");
        if (cartData) {
          this.cartlist = JSON.parse(cartData);
        }
      } catch (error) {
        console.error("从本地存储加载购物车数据失败", error);
        this.cartlist = [];
      }
    },

    // 保存购物车数据到本地
    saveCartData() {
      uni.setStorageSync("cartlist", JSON.stringify(this.cartlist));
    },

    shopsdata(id2) {
      console.log(id2);
      uni.request({
        url: `http://localhost:3000/hotList?_id=${id2}`,
        success: (res) => {
          this.shops = res.data;
        },
      });
    },
    switchView(index) {
      if (this.flag === 1) {
        this.flag = index;
        this.index = index;
        uni.request({
          url: `http://localhost:3000/products?shopid=${this.shopid}`,
          success: (res) => {
            this.products = res.data.map(product => ({
              ...product,
              id: product._id // 将后端返回的_id映射到id字段
            }));
          }
        });
      } else if (this.flag === 2) {
        this.flag = index;
        this.index = index;
        uni.request({
          url: `http://localhost:3000/seck?shopid=${this.shopid}`,
          success: (res) => {
            this.products = res.data;
          },
        });
      } else if (this.flag === 3) {
        this.flag = index;
        this.index = index;
        uni.request({
          url: `http://localhost:3000/fruit?shopid=${this.shopid}`,
          success: (res) => {
            this.products = res.data;
          },
        });
      }
    },
    
    // 切换购物车显示/隐藏
    toggleCart() {
      this.showCart = !this.showCart;
    },
    
    buttonhaddcart(product) {
      // 检查商品是否已经在购物车中（使用映射后的id）
      const existingItem = this.cartlist.find(
        item => item.id === product.id && item.shopId === this.shopid // 确保使用正确的id
      );
      
      if (existingItem) {
        existingItem.quantity++;
        uni.showToast({ title: '商品数量已增加', icon: 'success' });
      } else {
        const newItem = {
          id: product.id, // 使用正确的商品唯一标识
          name: product.name,
          price: product.price,
          imgUrl: product.imgUrl,
          quantity: 1,
          shopId: this.shopid,
          shopName: this.shops[0]?.name || "未知超市",
          selected: true
        };
        this.cartlist.push(newItem);
        uni.showToast({ title: '已加入购物车', icon: 'success' });
      }
      this.saveCartData();
    },
    
    // 切换单个商品的选择状态
    toggleItemSelect(item) {
      item.selected = !item.selected;
      this.saveCartData();
    },
    
    // 全选/取消全选
    toggleSelectAll() {
      const shouldSelectAll = !this.isAllSelected;
      this.filteredCartList.forEach(item => {
        item.selected = shouldSelectAll;
      });
      this.saveCartData();
    },
    
    // 增加商品数量
    increaseQuantity(item) {
      item.quantity++;
      this.saveCartData();
    },
    
    // 减少商品数量
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
        this.saveCartData();
      } else {
        // 如果数量为1，再次减少则从购物车移除
        this.removeFromCart(item);
      }
    },
    
    // 从购物车移除商品
    removeFromCart(item) {
      const index = this.cartlist.findIndex(
        cartItem => cartItem.id === item.id // 使用正确的id字段对比
      );
      if (index !== -1) {
        this.cartlist.splice(index, 1);
        this.saveCartData();
        uni.showToast({
          title: '已移除商品',
          icon: 'success'
        });
      }
    },
    
    // 清空当前超市购物车
    clearCurrentSupermarketCart() {
      this.cartlist = this.cartlist.filter(item => item.shopId !== this.shopid);
      this.saveCartData();
      uni.showToast({
        title: '购物车已清空',
        icon: 'success'
      });
    },
    
    // 结算
    checkout() {
      if (this.selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }

      // 这里可以添加结算逻辑，比如跳转到订单确认页面
      uni.showToast({
        title: `结算 ${this.selectedCount} 件商品，总价 ¥${this.totalPrice}`,
        icon: 'none'
      });
      uni.switchTab({
        url: '/pages/cart/index'
      });
    }
  }
};
</script>

<style scoped>
/* 通用图片样式 */
img {
  display: block;
  max-width: 100%;
  height: auto;
  object-fit: cover;
}

/* 店铺图片 */
.shop-image {
  width: 70px;
  height: 70px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 商品图片 */
.product-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}

/* 购物车图标图片 */
.cart-icon-image {
  width: 30px;
  height: 30px;
}

/* 购物车商品图片 */
.cart-item-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

/* 其他样式保持不变 */
.content .header .listcontent {
  margin-top: 20px;
  width: 100%;
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid #eee;
  margin-left: 20px;
  padding-bottom: 20px;
}
.content .header .listcontent .listitem .listrow {
  display: flex;
  flex-direction: row;
  padding-top: 10px;
  padding-bottom: 10px;
  font-size: 14px;
  color: #666;
}
.content .header .listcontent .listitem .listrow view {
  margin-right: 20px;
}
.content .header .listcontent .listcon {
  margin-left: 20px;
  font-size: 18px;
  flex: 1;
}
.slogan {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 5px;
}
.content .header .search input {
  border: 1px solid aliceblue;
  border-radius: 2ch;
  width: 50%;
  height: 40px;
  background-color: aliceblue;
  margin-top: 15px;
  margin-left: 10px;
}
/* 中间 */
.content .middleshops {
  display: flex;
}
.content .middleshops .click {
  width: 20%;
  background-color: rgb(245, 248, 248);
}
.content .middleshops .click .item {
  width: 100%;
  height: 40px;
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}
.content .middleshops .click .item.active {
  background-color: rgb(88, 165, 247);
  color: white;
}
.content .middleshops .message {
  width: 80%;
}
.message .itemlist {
  display: flex;
  margin-left: 20px;
  align-items: center;
}
.message .i {
  margin-bottom: 20px;
}
.message .shop {
  margin-top: 10px;
  width: 100%;
}
.message .shop .itemlist {
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}
.itemlist .con {
  margin-right: 15px;
}
.itemlist .button {
  display: flex;
  align-items: center;
  margin-right: 20px;
}
.itemlist .button button {
  margin-right: 10px;
  margin-left: 10px;
  border-radius: 5pt;
  margin: 0 auto;
  color: #f0f0f0;
  background-color: rgb(88, 165, 247);
  font-size: 12px;
  padding: 0 10px;
  height: 30px;
  line-height: 30px;
}
.itemlist .con .title {
  margin-bottom: 5px;
  font-weight: bold;
  font-size: 16px;
}
.itemlist .con .row {
  margin-top: 5px;
  display: flex;
  align-items: center;
}
.itemlist .con .row .price {
  color: #e74c3c;
  font-size: 16px;
  font-weight: bold;
}
.itemlist .con .row .oldPrice {
  color: #999;
  padding-left: 10px;
  text-decoration: line-through;
  font-size: 12px;
}

/* 购物车图标样式 */
.cart-icon {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 50px;
  height: 50px;
  background-color: #43a8ec;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  z-index: 999;
  box-shadow: 0 2px 10px rgba(0,0,0,0.2);
}

.cart-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #e74c3c;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 购物车面板样式 */
.cart-panel {
  position: fixed;
  bottom: -100%;
  left: 0;
  right: 0;
  height: 60vh;
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1001;
  transition: bottom 0.3s ease;
}

.cart-panel.show {
  bottom: 0;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.cart-title {
  font-size: 18px;
  font-weight: bold;
}

.clear-cart {
  font-size: 14px;
  color: #666;
}

.cart-items {
  height: calc(60vh - 150px);
  overflow-y: auto;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-select {
  margin-right: 10px;
}

.item-image {
  margin-right: 10px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.item-price {
  font-size: 16px;
  color: #f40;
  font-weight: bold;
}

.item-quantity {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 25px;
  height: 25px;
  line-height: 25px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 50%;
  font-size: 16px;
}

.quantity-number {
  margin: 0 10px;
  min-width: 20px;
  text-align: center;
}

.cart-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  background-color: #43a8ec;
  border-top: 1px solid #eee;
}

.select-all {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: white;
}

.select-all text {
  margin-left: 5px;
}

.total-price {
  font-size: 14px;
  margin-left: 20px;
  color: white;
}

.price {
  color: white;
  font-weight: bold;
  font-size: 16px;
}

.checkout-btn {
  background-color: #fff;
  color: #43a8ec;
  padding: 8px 15px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
}

/* 遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .shop-image {
    width: 60px;
    height: 60px;
  }
  
  .product-image {
    width: 50px;
    height: 50px;
  }
  
  .content .header .listcontent .listcon {
    font-size: 16px;
  }
  
  .content .header .listcontent .listitem .listrow view {
    margin-right: 10px;
    font-size: 12px;
  }
  
  .itemlist .con .title {
    font-size: 14px;
  }
  
  .itemlist .button button {
    font-size: 10px;
    padding: 0 8px;
  }
}
</style>